package com.aiyige.page.webview.model;

import org.apache.commons.collections4.queue.CircularFifoQueue;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PreloadTaskQueue {
    CircularFifoQueue<PreloadTask> queue;
    Lock mutex;
    Condition waitCondition;


    public PreloadTaskQueue() {
        queue = new CircularFifoQueue<>(10);
        mutex = new ReentrantLock();
        waitCondition = mutex.newCondition();
    }


    public void submitTask(PreloadTask task) {
        mutex.lock();
        if (task.type == PreloadTask.TYPE_SHUTDOWN) {
            queue.clear();
        }
        queue.add(task);
        waitCondition.signalAll();
        mutex.unlock();
    }

    public PreloadTask getTask() {
        PreloadTask task;
        mutex.lock();
        if (queue.isEmpty()) {
            try {
                waitCondition.await();
            } catch (Exception e) {
                try {
                    mutex.unlock();
                } catch (Exception ex) {

                }
            }
        }
        task = queue.poll();
        mutex.unlock();
        return task;
    }

}
